package com.logistics.service.impl;

import com.logistics.common.Result;
import com.logistics.entity.Warehouse;
import com.logistics.service.DashboardService;
import com.logistics.service.LogisticsOrderService;
import com.logistics.service.TransportRecordService;
import com.logistics.service.WarehouseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class DashboardServiceImpl implements DashboardService {

    @Autowired
    private LogisticsOrderService orderService;

    @Autowired
    private TransportRecordService transportService;

    @Autowired
    private WarehouseService warehouseService;

    @Override
    @Cacheable(value = "dashboard", key = "'statistics'")
    public Result<Map<String, Object>> getStatistics() {
        try {
            Map<String, Object> statistics = new HashMap<>();
            
            // 获取订单统计
            Result<List<Map<String, Object>>> ordersResult = orderService.listOrders();
            if (ordersResult.getCode() == 200) {
                List<Map<String, Object>> orders = ordersResult.getData();
                statistics.put("totalOrders", orders.size());
                statistics.put("transportingOrders", orders.stream()
                    .filter(order -> "运输中".equals(order.get("status")))
                    .count());
            }
            
            // 获取仓库统计
            Result<List<Map<String, Object>>> warehousesResult = warehouseService.listWarehouses();
            if (warehousesResult.getCode() == 200) {
                statistics.put("totalWarehouses", warehousesResult.getData().size());
            }
            
            return Result.success(statistics);
        } catch (Exception e) {
            return Result.error("获取统计数据失败：" + e.getMessage());
        }
    }

    @Override
    @Cacheable(value = "dashboard", key = "'orderStatus'")
    public Result<List<Map<String, Object>>> getOrderStatus() {
        try {
            Result<List<Map<String, Object>>> ordersResult = orderService.listOrders();
            if (ordersResult.getCode() != 200) {
                return Result.error("获取订单数据失败");
            }
            
            List<Map<String, Object>> orders = ordersResult.getData();
            Map<String, Long> statusCount = new HashMap<>();
            
            for (Map<String, Object> order : orders) {
                String status = (String) order.get("status");
                statusCount.merge(status, 1L, Long::sum);
            }
            
            List<Map<String, Object>> result = new ArrayList<>();
            statusCount.forEach((status, count) -> {
                Map<String, Object> item = new HashMap<>();
                item.put("status", status);
                item.put("count", count);
                result.add(item);
            });
            
            return Result.success(result);
        } catch (Exception e) {
            return Result.error("获取订单状态分布失败：" + e.getMessage());
        }
    }

    @Override
    @Cacheable(value = "dashboard", key = "'warehouseUsage'")
    public Result<List<Map<String, Object>>> getWarehouseUsage() {
        try {
            Result<List<Map<String, Object>>> warehousesResult = warehouseService.listWarehouses();
            if (warehousesResult.getCode() != 200) {
                return Result.error("获取仓库数据失败");
            }
            
            List<Map<String, Object>> warehouses = warehousesResult.getData();
            List<Map<String, Object>> result = new ArrayList<>();
            
            for (Map<String, Object> warehouse : warehouses) {
                Map<String, Object> item = new HashMap<>();
                item.put("name", warehouse.get("name"));
                item.put("usage", calculateUsage(warehouse));
                result.add(item);
            }
            
            return Result.success(result);
        } catch (Exception e) {
            return Result.error("获取仓库使用率失败：" + e.getMessage());
        }
    }

    @Override
    @Cacheable(value = "dashboard", key = "'orderTrend'")
    public Result<List<Map<String, Object>>> getOrderTrend() {
        try {
            LocalDate endDate = LocalDate.now();
            LocalDate startDate = endDate.minusDays(6);
            
            Result<List<Map<String, Object>>> ordersResult = orderService.listOrders();
            if (ordersResult.getCode() != 200) {
                return Result.error("获取订单数据失败");
            }
            
            List<Map<String, Object>> orders = ordersResult.getData();
            Map<String, Long> dailyCount = new HashMap<>();
            
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            for (LocalDate date = startDate; !date.isAfter(endDate); date = date.plusDays(1)) {
                dailyCount.put(date.format(formatter), 0L);
            }
            
            for (Map<String, Object> order : orders) {
                LocalDateTime createTime = (LocalDateTime) order.get("createTime");
                if (createTime != null) {
                    String date = createTime.toLocalDate().format(formatter);
                    if (dailyCount.containsKey(date)) {
                        dailyCount.merge(date, 1L, Long::sum);
                    }
                }
            }
            
            List<Map<String, Object>> result = new ArrayList<>();
            dailyCount.forEach((date, count) -> {
                Map<String, Object> item = new HashMap<>();
                item.put("date", date);
                item.put("count", count);
                result.add(item);
            });
            
            return Result.success(result);
        } catch (Exception e) {
            return Result.error("获取订单趋势失败：" + e.getMessage());
        }
    }

    private double calculateUsage(Map<String, Object> warehouse) {
        double capacity = ((Number) warehouse.get("capacity")).doubleValue();
        double usedCapacity = ((Number) warehouse.get("usedCapacity")).doubleValue();
        return capacity > 0 ? (usedCapacity / capacity) * 100 : 0;
    }
} 